package com.my.zl.console.service.autocode.impl;

import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.my.zl.common.dto.ReqDTO;
import com.my.zl.common.dto.advancedQuery.PageQueryDTO;
import com.my.zl.common.enums.resp.GlobalEnum;
import com.my.zl.common.exception.BizException;
import com.my.zl.common.utils.CopyUtil;
import com.my.zl.console.common.config.MyselfProperties;
import com.my.zl.console.common.constant.AutocodeC;
import com.my.zl.console.common.constant.AutocodeRespE;
import com.my.zl.console.dao.autocode.ZlTemplateDtlMapper;
import com.my.zl.console.dao.autocode.ZlTemplateMapper;
import com.my.zl.console.dto.autocode.template.ReqTemplateAddDTO;
import com.my.zl.console.dto.autocode.template.ReqTemplateDelDTO;
import com.my.zl.console.dto.autocode.template.ReqTemplateDetailDTO;
import com.my.zl.console.dto.autocode.template.ReqTemplateEditDTO;
import com.my.zl.console.dto.autocode.template.ReqTemplateQueryDTO;
import com.my.zl.console.dto.autocode.template.ReqTemplateStateDTO;
import com.my.zl.console.dto.autocode.template.ResTemplateAddDTO;
import com.my.zl.console.dto.autocode.template.ResTemplateDelDTO;
import com.my.zl.console.dto.autocode.template.ResTemplateDetailDTO;
import com.my.zl.console.dto.autocode.template.ResTemplateEditDTO;
import com.my.zl.console.dto.autocode.template.ResTemplateQueryDTO;
import com.my.zl.console.dto.autocode.template.ResTemplateStateDTO;
import com.my.zl.console.dto.autocode.template.ResTemplateVO2;
import com.my.zl.console.entity.autocode.ZlTemplate;
import com.my.zl.console.po.autocode.template.ZlTemplateVo;
import com.my.zl.console.service.autocode.ITemplateService;
import com.my.zl.console.service.base.BaseManager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;

/**
 * 模板信息
 * @author ZL
 */
@Service
public class TemplateServiceImpl extends BaseManager implements ITemplateService {

    @Autowired
    private ZlTemplateMapper templateMapper;
    @Autowired
    private ZlTemplateDtlMapper templateDtlMapper;
    @Autowired
    private MyselfProperties myselfProperties;
    
    @Override
    public ResTemplateQueryDTO queryTemplateList(ReqTemplateQueryDTO reqInfo,PageQueryDTO page) throws Exception{
        // TODO Auto-generated method stub
        ResTemplateQueryDTO resDTO = BeanUtil.copyProperties(page, ResTemplateQueryDTO.class);
        if(StringUtils.isNotBlank(reqInfo.getTemplateTitle())){
            reqInfo.setTemplateTitle("%"+reqInfo.getTemplateTitle()+"%");
        }
        Map<String,Object> paramMap = new HashMap<>();
        paramMap = BeanUtil.beanToMap(reqInfo);
        
        pageHandle(page);//处理分页数据
        //当效率不行时自行计数，或完全自行分页，先查询总数，如果为0不用再次查询了；开启计数：true是,false否
        //临近第一条SQL查询语句自动分页,如果未消费时(即后面没有触发SQL查询)则需主动调用pageHp.clear()清理
        Page<Object> pageHp = PageHelper.startPage(page.getPage(), page.getLimit(),page.getSortorder());
        List<ZlTemplateVo> list = templateMapper.selectListPage(paramMap);
        resDTO.setData(CopyUtil.copyList(list, ResTemplateVO2.class));
        resDTO.setCount(pageHp.getTotal());
        
        return resDTO;
    }
    
    @Override
    public ResTemplateDetailDTO queryTemplateDetail(ReqTemplateDetailDTO reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ResTemplateDetailDTO res = new ResTemplateDetailDTO();
        
        Map<String,Object> paramMap = new HashMap<>();
        paramMap = BeanUtil.beanToMap(reqInfo);
        ZlTemplate view = templateMapper.selectOneByMap(paramMap);
        BeanUtil.copyProperties(view, res);
        return res;
    }
    
    @Override
    public ResTemplateAddDTO insertTemplateInfo(ReqDTO<ReqTemplateAddDTO> reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqTemplateAddDTO reqData = reqInfo.getReqData();
        ResTemplateAddDTO res = new ResTemplateAddDTO();
        Instant time = getSystemTime().getUtcTime();
        
        ZlTemplate record = new ZlTemplate();
        BeanUtil.copyProperties(reqData, record);
        
        initCreateInfo(record, reqInfo, time);
        record.setTemplateId(IdUtil.simpleUUID());
        record.setDataStatus(AutocodeC.DataStatus.ENABLE.getCode());//状态
        record.setTemplatePath(filePath(myselfProperties.getAutocodePathRoot(),myselfProperties.getAutocodePathMajor(),myselfProperties.getAutocodePathTemplate()
                ,new String[]{record.getTemplateId()}));
        
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("templateId",record.getTemplateId());
        //检查主键是否冲突
        if(templateMapper.countExistKey(paramMap)>0){
            throw new BizException(GlobalEnum.DUPLICATE_PRIMARY_KEY);
        }
        
        templateMapper.insertSelective(record);
        
        ZlTemplate keyInfo = templateMapper.selectOneByMap(paramMap);
        BeanUtil.copyProperties(keyInfo, res);
        
        return res;
    }
    
    @Override
    public ResTemplateEditDTO updateTemplateInfo(ReqDTO<ReqTemplateEditDTO> reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqTemplateEditDTO reqData = reqInfo.getReqData();
        ResTemplateEditDTO res = new ResTemplateEditDTO();
        Instant time = getSystemTime().getUtcTime();
        
        ZlTemplate record = new ZlTemplate();
        BeanUtil.copyProperties(reqData, record);
        
        initUpdateInfo(record, reqInfo, time);
        
        templateMapper.updateByPrimaryKeySelective(record);
        
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("templateId",record.getTemplateId());
        ZlTemplate keyInfo = templateMapper.selectOneByMap(paramMap);
        BeanUtil.copyProperties(keyInfo, res);
        
        return res;
    }
    
    @Override
    public ResTemplateDelDTO deleteTemplateInfo(ReqDTO<ReqTemplateDelDTO> reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqTemplateDelDTO reqData = reqInfo.getReqData();
        ResTemplateDelDTO res = new ResTemplateDelDTO();
        Instant time = getSystemTime().getUtcTime();
        
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("templateId",reqData.getTemplateId());
        if(templateDtlMapper.countExistKey(paramMap) > 0){
            throw new BizException(AutocodeRespE.DELETE_NOT_ALLOWED);
        }
        
        paramMap = BeanUtil.beanToMap(reqData);
        templateMapper.deleteByMap(paramMap);
        
        return res;
    }
    
    @Override
    public ResTemplateStateDTO updateTemplateState(ReqDTO<ReqTemplateStateDTO> reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqTemplateStateDTO reqData = reqInfo.getReqData();
        ResTemplateStateDTO res = new ResTemplateStateDTO();
        Instant time = getSystemTime().getUtcTime();
         
        ZlTemplate record = new ZlTemplate();
        BeanUtil.copyProperties(reqData, record);
        initUpdateInfo(record, reqInfo, time);
        templateMapper.updateByPrimaryKeySelective(record);
         
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("templateId",record.getTemplateId());
        ZlTemplate keyInfo = templateMapper.selectOneByMap(paramMap);
        BeanUtil.copyProperties(keyInfo, res);
        
        return res;
    }
}